package com.zenithmind.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.utils.BeanCopyUtils;
import com.zenithmind.task.mapper.TaskTemplateMapper;
import com.zenithmind.task.pojo.entity.TaskTemplate;
import com.zenithmind.task.pojo.query.TaskTemplateQuery;
import com.zenithmind.task.pojo.vo.TaskTemplateVO;
import com.zenithmind.task.service.TaskTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务模板服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskTemplateServiceImpl extends ServiceImpl<TaskTemplateMapper, TaskTemplate> implements TaskTemplateService {

    @Override
    public PageResult<TaskTemplateVO> getTaskTemplatePage(TaskTemplateQuery query, String userId) {
        Page<TaskTemplate> page = query.toPage();

        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(query.getName()), TaskTemplate::getName, query.getName())
               .eq(query.getStatus() != null, TaskTemplate::getStatus, query.getStatus())
               .eq(query.getIsPublic() != null, TaskTemplate::getIsPublic, query.getIsPublic());

        if (StringUtils.hasText(query.getKeyword())) {
            wrapper.and(w -> w.like(TaskTemplate::getName, query.getKeyword())
                             .or()
                             .like(TaskTemplate::getDescription, query.getKeyword()));
        }
        
        // 默认查询用户创建的或公开的模板
        wrapper.and(w -> w.eq(TaskTemplate::getCreatorId, userId)
                         .or()
                         .eq(TaskTemplate::getIsPublic, 1));

        wrapper.orderByDesc(TaskTemplate::getUsageCount)
               .orderByDesc(TaskTemplate::getCreateTime);

        IPage<TaskTemplate> result = page(page, wrapper);

        List<TaskTemplateVO> voList = result.getRecords().stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    public TaskTemplateVO getTaskTemplateById(String id, String userId) {
        TaskTemplate taskTemplate = getById(id);
        if (taskTemplate == null) {
            throw new BusinessException("任务模板不存在");
        }
        
        return convertToVO(taskTemplate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTaskTemplate(TaskTemplate taskTemplate, String userId) {
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskTemplate::getName, taskTemplate.getName())
               .eq(TaskTemplate::getCreatorId, userId);

        if (count(wrapper) > 0) {
            throw new BusinessException("模板名称已存在");
        }

        if (taskTemplate.getType() == null) {
            taskTemplate.setType(1); // 个人模板
        }
        if (taskTemplate.getIsPublic() == null) {
            taskTemplate.setIsPublic(0);
        }
        
        taskTemplate.setCreatorId(userId);
        
        boolean result = save(taskTemplate);
        if (result) {
            log.info("用户 {} 创建任务模板: {}", userId, taskTemplate.getName());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTaskTemplate(TaskTemplate taskTemplate, String userId) {
        TaskTemplate existing = getById(taskTemplate.getId());
        if (existing == null) {
            throw new BusinessException("任务模板不存在");
        }

        // 权限检查
        if (!existing.getCreatorId().equals(userId)) {
            throw new BusinessException("无权限修改该模板");
        }

        // 检查模板名称是否已存在（排除自己）
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskTemplate::getName, taskTemplate.getName())
               .eq(TaskTemplate::getCreatorId, userId)
               .eq(TaskTemplate::getStatus, 1)
               .ne(TaskTemplate::getId, taskTemplate.getId());

        if (count(wrapper) > 0) {
            throw new BusinessException("模板名称已存在");
        }

        boolean result = updateById(taskTemplate);
        
        if (result) {
            log.info("用户 {} 更新任务模板: {}", userId, taskTemplate.getName());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTaskTemplate(String id, String userId) {
        TaskTemplate taskTemplate = getById(id);
        if (taskTemplate == null) {
            throw new BusinessException("任务模板不存在");
        }

        // 权限检查
        if (!taskTemplate.getCreatorId().equals(userId)) {
            throw new BusinessException("无权限删除该模板");
        }

        boolean result = removeById(id);
        
        if (result) {
            log.info("用户 {} 删除任务模板: {}", userId, taskTemplate.getName());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteTaskTemplates(List<String> ids, String userId) {
        for (String id : ids) {
            deleteTaskTemplate(id, userId);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTemplateFromTask(String taskId, String templateName, String templateDescription, String userId) {
        // TODO: 从任务创建模板的具体实现
        // 1. 获取任务信息
        // 2. 创建模板记录
        // 3. 复制任务的相关配置
        
        TaskTemplate taskTemplate = new TaskTemplate();
        taskTemplate.setName(templateName);
        taskTemplate.setDescription(templateDescription);
        taskTemplate.setCreatorId(userId);
        taskTemplate.setType(1); // 个人模板
        taskTemplate.setIsPublic(0); // 私有
        taskTemplate.setUsageCount(0);
        taskTemplate.setStatus(1); // 有效
        
        boolean result = save(taskTemplate);
        
        if (result) {
            log.info("用户 {} 从任务 {} 创建模板: {}", userId, taskId, templateName);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTaskFromTemplate(String templateId, Map<String, Object> customData, String userId) {
        TaskTemplate template = getById(templateId);
        if (template == null) {
            throw new BusinessException("任务模板不存在");
        }

        // TODO: 从模板创建任务的具体实现
        // 1. 根据模板配置创建任务
        // 2. 应用自定义数据
        // 3. 更新模板使用次数
        
        // 更新使用次数
        template.setUsageCount(template.getUsageCount() + 1);
        updateById(template);
        
        log.info("用户 {} 从模板 {} 创建任务", userId, template.getName());
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyTemplate(String templateId, String newTemplateName, String userId) {
        TaskTemplate original = getById(templateId);
        if (original == null) {
            throw new BusinessException("原模板不存在");
        }

        TaskTemplate newTemplate = BeanCopyUtils.copyBean(original, TaskTemplate.class);
        newTemplate.setId(null);
        newTemplate.setName(newTemplateName);
        newTemplate.setCreatorId(userId);
        newTemplate.setUsageCount(0);
        newTemplate.setIsPublic(0); // 复制的模板默认为私有

        boolean result = save(newTemplate);
        
        if (result) {
            log.info("用户 {} 复制模板: {} -> {}", userId, original.getName(), newTemplateName);
        }
        
        return result;
    }

    @Override
    public List<TaskTemplateVO> getPublicTemplates(String userId) {
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskTemplate::getIsPublic, 1)
               .eq(TaskTemplate::getStatus, 1)
               .orderByDesc(TaskTemplate::getUsageCount)
               .orderByDesc(TaskTemplate::getCreateTime);

        List<TaskTemplate> templates = list(wrapper);
        
        return templates.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }

    @Override
    public List<TaskTemplateVO> getUserCreatedTemplates(String userId) {
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskTemplate::getCreatorId, userId)
               .eq(TaskTemplate::getStatus, 1)
               .orderByDesc(TaskTemplate::getCreateTime);

        List<TaskTemplate> templates = list(wrapper);
        
        return templates.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }

    @Override
    public List<TaskTemplateVO> getPopularTemplates(Integer limit, String userId) {
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskTemplate::getStatus, 1)
               .gt(TaskTemplate::getUsageCount, 0)
               .orderByDesc(TaskTemplate::getUsageCount)
               .last("LIMIT " + (limit != null ? limit : 10));

        List<TaskTemplate> templates = list(wrapper);
        
        return templates.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }

    @Override
    public List<TaskTemplateVO> searchTemplates(String keyword, String userId) {
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskTemplate::getStatus, 1)
               .and(w -> w.like(TaskTemplate::getName, keyword)
                         .or()
                         .like(TaskTemplate::getDescription, keyword))
               .orderByDesc(TaskTemplate::getUsageCount)
               .orderByAsc(TaskTemplate::getName);

        List<TaskTemplate> templates = list(wrapper);
        
        return templates.stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setTemplatePublic(String templateId, Boolean isPublic, String userId) {
        TaskTemplate template = getById(templateId);
        if (template == null) {
            throw new BusinessException("任务模板不存在");
        }

        // 权限检查
        if (!template.getCreatorId().equals(userId)) {
            throw new BusinessException("无权限修改该模板");
        }

        template.setIsPublic(isPublic ? 1 : 0);
        boolean result = updateById(template);
        
        if (result) {
            log.info("用户 {} 设置模板 {} 为{}", userId, template.getName(), isPublic ? "公共" : "私有");
        }
        
        return result;
    }

    /**
     * 转换为VO对象
     */
    private TaskTemplateVO convertToVO(TaskTemplate taskTemplate) {
        TaskTemplateVO vo = BeanCopyUtils.copyBean(taskTemplate, TaskTemplateVO.class);
        
        // 设置模板类型文本
        vo.setTemplateTypeText(getTemplateTypeText(taskTemplate.getType()));
        
        // 设置状态文本
        vo.setStatusText(getStatusText(taskTemplate.getStatus()));
        
        // 设置可见性文本
        vo.setVisibilityText(taskTemplate.getIsPublic() == 1 ? "公共" : "私有");
        
        return vo;
    }

    /**
     * 获取模板类型文本
     */
    private String getTemplateTypeText(Integer templateType) {
        switch (templateType) {
            case 1: return "个人模板";
            case 2: return "团队模板";
            case 3: return "系统模板";
            default: return "未知";
        }
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        switch (status) {
            case 1: return "有效";
            case 0: return "无效";
            default: return "未知";
        }
    }
}
